import Taro from "@tarojs/taro";
import { show, showErrorModal, showLong } from "@/utils/common";
import { getHost } from "@/constants/Constant";
import store from "@/store";

// 错误定义
const HTTP_STATUS = {
    SUCCESS: 200,
    CREATED: 201,
    ACCEPTED: 202,
    CLIENT_ERROR: 400,
    AUTHENTICATE: 401,
    FORBIDDEN: 403,
    NOT_FOUND: 404,
    SERVER_ERROR: 500,
    BAD_GATEWAY: 502,
    SERVICE_UNAVAILABLE: 503,
    GATEWAY_TIMEOUT: 504,
};

// 拦截器
const interceptor = (chain) => {
    const requestParams = chain.requestParams;
    return chain.proceed(requestParams).then((res) => {
        if (res && res.header && res.header["Set-Cookie"]) {
            Taro.setStorageSync("sessionid", res.header["Set-Cookie"]);
        }
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
            show("请求资源不存在");
            return Promise.reject("请求资源不存在");
        } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
            show("服务端出现问题");
            return Promise.reject("服务端出现问题");
        } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
            show("无权访问");
            return Promise.reject("无权访问");
        } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
            show("需要鉴权");
            return Promise.reject("需要鉴权");
        } else {
            return res.data;
        }
    });
};

// 添加拦截器
Taro.addInterceptor(interceptor);
if (process.env.NODE_ENV === "development") {
    Taro.addInterceptor(Taro.interceptors.logInterceptor);
}

//主机地址根据当前激活环境
const request = ({ url, data = {}, method = "get", header = {} }) => {
    const BASE_URL = getHost();
    const handleHeader = {
        "content-type": "application/json",
        "x-auth-token": Taro.getStorageSync("token"),
        cookie: Taro.getStorageSync("sessionid"),
        ...header,
    };
    return new Promise((resolve, reject) => {
        const options = {
            url: `${BASE_URL}${url}`,
            data,
            method,
            header: handleHeader,
        };
        Taro.request({
            ...options,
            success(res) {
                Taro.hideLoading();
                const { data: d } = res || {};
                const { code, message, data: dd } = d || {};
                if (code != 200) {
                    showLong(message);
                    reject(message);
                } else if (code == 403) {
                    removeStorageSync("token");
                    store.dispatch({
                        type: "user_reset",
                    });
                    showLong(message);
                    reject(message);
                }
                resolve(dd);
            },
            fail(e) {
                reject(e);
            },
        });
    });
};

export default request;
